package hydrap2p.proxy.manager;

import hydrap2p.ServiceLocation;
import hydrap2p.helper.Utility;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;

import org.dtools.ini.AdvancedIniFile;
import org.dtools.ini.IniFile;
import org.dtools.ini.IniFileReader;
import org.dtools.ini.IniItem;
import org.dtools.ini.IniSection;

public class Configuration {

	private int listen;
	private List<ServiceLocation> peers;
	public Configuration() throws NumberFormatException, FileNotFoundException
	{
		// load configuration
		peers=new LinkedList<ServiceLocation>();
		listen=-1;
		
		String confLocation=Utility.getUserConfigurationPath();
		String myconfLocation=Utility.appendPath(confLocation,"proxymanager.ini");
		File myconf = new File(myconfLocation);
		if (!myconf.exists())
		{
			String sharedconfLocation=Utility.appendPath(Utility.getSharedConfigurationPath(), "proxymanager.ini");
			File sharedconf = new File(sharedconfLocation);
			if (!sharedconf.exists())
				throw new FileNotFoundException(myconfLocation);
			else
				myconf=sharedconf;
		}
		IniFile conf = new AdvancedIniFile();
		try {
			new IniFileReader(conf,myconf).read();
		} catch (IOException e) {	// could not open the file
			throw new FileNotFoundException(myconfLocation);
		}
		IniSection section=conf.getSection("proxymanager");
		if (section!=null)
		{
			Collection<IniItem> items=section.getItems();
			for (IniItem item : items)
			{
				if (item.getName().equals("listen"))
				{
					listen=Integer.parseInt(item.getValue());
				}
				if (item.getName().equals("peer"))
				{
					String[] split=item.getValue().split(":",2);
					ServiceLocation temp=new ServiceLocation();
					try {
						temp.address=split[0];
						temp.port=Integer.parseInt(split[1]);
					}
					catch (Exception e)
					{
						System.err.println("Could not parse peer configuration \""+item.getValue()+"\": "+e.getClass()+": "+e.getLocalizedMessage());
						continue;
					}
					peers.add(temp);
				}
			}
			if (listen==-1 && peers.size()==0)
				throw new FileNotFoundException("Port configuration could not be parsed, need either a listen or a peer directive");
		}
	}
	
	public int getListenPort()
	{
		return listen;
	}
	public List<ServiceLocation> getPeers()
	{
		return peers;
	}
}
